package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author Administrator
 * @Description
 * 该任务负责与指定的客户端进行交互
 * @date 2022/5/12 16:34
 **/
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try {
            //解析请求
            HttpServletRequest request = new HttpServletRequest(socket);


                //处理请求
                String uri = request.getUri();
                //发送响应
                File rootDic = new File(
                        ClientHandler.class.getClassLoader().getResource(".").toURI()
                );
                File staticDic = new File(rootDic, "static");

                File file = new File(staticDic, uri);

                //发送状态行
                int statesCode;
                String statesReason;
                if (file.isFile()) {
                    statesCode = 200;
                    statesReason = "OK";
                }else {
                    statesCode = 404;
                    statesReason = "NotFound";
                    file = new File(staticDic, "/root/404.html");
                }
                println("HTTP/1.1 " + statesCode + " " + statesReason);
                //发送响应头

                println("Content-Type: text/html");
                println("Content-Length: " + file.length());

                println("");
                //发送响应正文
                OutputStream out = socket.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                byte[]data = new byte[1024 * 10];
                int len;
                while ((len = fis.read(data))!= -1){
                    out.write(data, 0, len);
                }

                System.out.println("响应发送完毕!!!!!!!!!!!!!!!!!!!");

            }
        catch (IOException | URISyntaxException e) {
                e.printStackTrace();
            }


    }


    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }

}
